/* eslint-disable */
<template>
  <q-page>
    <div class="ocr-id-card row fit q-pa-xl">
      <div class="col flex flex-center box-content">
        <img :src="img" v-if="img" />
        <q-file
          v-else
          ref="fileField"
          filled
          v-model="uploadField"
          label="点击或者拖拽适任证正面到此处"
          input-style="height:200px;width:300px"
          :max-files="1"
          @input="fileChange"
        >
          <template v-slot:prepend>
            <q-icon name="attach_file" />
          </template>
        </q-file>
      </div>

      <div class="col column bg-grey-1">
        <q-card class="q-ma-md q-ma-xl">
          <q-list bordered class="card-info">
            <q-item>
              <q-item-section>证书名称：</q-item-section>
              <q-item-section>
                {{ idCard.cert_code }}
              </q-item-section>
            </q-item>
            <q-separator />
            <q-item>
              <q-item-section>证书编号：</q-item-section>
              <q-item-section>
                {{ idCard.cert_num }}
              </q-item-section>
            </q-item>
            <q-separator />
            <q-item>
              <q-item-section>签发日期：</q-item-section>
              <q-item-section>
                {{ idCard.issue_date }}
              </q-item-section>
            </q-item>
            <q-separator />
            <q-item>
              <q-item-section>有效期至</q-item-section>
              <q-item-section>
                {{ idCard.validity_term }}
              </q-item-section>
            </q-item>
          </q-list>
          <q-table
            title="合格证列表"
            :data="certificateList"
            :columns="columns"
            row-key="title"
            hide-bottom
            :rows-per-page-options="[0]"
          />
        </q-card>
      </div>
    </div>
  </q-page>
</template>

<script>
import { imageOcr } from "boot/api/index";
import { fileToBase64 } from "components/utils/FileCompress";

export default {
  props: {},
  data() {
    return {
      uploadField: null,
      img: "",
      idCard: {
        cert_code: "OSV",
        cert_num: "",
        issue_date: "",
        validity_term: "",
      },
      idCardEmpty: {
        cert_code: "OSV",
        cert_num: "",
        issue_date: "",
        validity_term: "",
      },
      title: "",
      clause: "",
      dateIssue: "",
      dateExpiry: "",
      columns: [
        {
          name: "title",
          label: "合格证名称",
          field: "title",
          align: "left",
        },
        {
          name: "clause",
          label: "适用公约条款",
          field: "clause",
          align: "left",
        },
        {
          name: "dateIssue",
          label: "签发日期",
          field: "dateIssue",
          align: "left",
        },
        {
          name: "dateExpiry",
          label: "有效期至",
          field: "dateExpiry",
          align: "left",
        },
      ],
      certificateList: [],
    };
  },
  computed: {},
  methods: {
    filterEn(value) {
      return value.replace(/[u4e00-u9fa5|,]+/gi, " ");
    },
    trimColon(str) {
      if (str.indexOf(":") > -1) {
        [, str] = str.split(":");
      }
      if (str.indexOf("：") > -1) {
        [, str] = str.split("：");
      }
      return str;
    },
    trimNotCn(str) {
      return str.replace(/[u4e00-u9fa5|,]+/gi, "");
    },
    getDate(str) {
      str = this.trimColon(str);
      let date = `${str.split("日")[0]}日`;
      if (date.length > 11) {
        date = date.substring(date.length - 11);
      }
      return date;
    },
    // 判断字符串是否全是中文
    isAllChinese(str) {
      return /^[\u4E00-\u9FA5]+$/.test(str);
    },
    // saxCertificateList(data) {
    //   let found = false;
    //   const keywordList = [
    //     "Date of Issue",
    //     "Clause",
    //     "Title of the Certificate(s)",
    //     "Date of Expiry",
    //   ];
    //   let certificate = {
    //     title: "",
    //     clause: "",
    //     dateIssue: "",
    //     dateExpiry: "",
    //   };
    //   for (let i = 0; i < data.length; i += 1) {
    //     const field = data[i];
    //     const { text } = field;
    //     if (keywordList.indexOf(text) > -1) {
    //       found = true;
    //     } else if (found) {
    //       // 如果有年月日   以VI开头  或者全是中文   精通教生艇筱和救助艇培训 那么就是我们想要的
    //       if (
    //         text.indexOf("年") > -1 &&
    //         text.indexOf("月") > -1 &&
    //         text.indexOf("日") > -1
    //       ) {
    //         if (text.length === 22) {
    //           const [dateIssue, dateExpiry] = text.split("日");
    //           certificate.dateIssue = `${dateIssue}日`;
    //           certificate.dateExpiry = `${dateExpiry}日`;
    //         } else if (!certificate.dateIssue) {
    //           certificate.dateIssue = text;
    //         } else {
    //           certificate.dateExpiry = text;
    //         }
    //       } else if (text.indexOf("A-V") > -1) {
    //         if (text.indexOf("V") !== 0) {
    //           certificate.clause = `V${text.substring(1)}`;
    //         } else {
    //           certificate.clause = text;
    //         }
    //       } else if (this.isAllChinese(text)) {
    //         certificate.title = text;
    //       }
    //       // 获取全了，就换一个
    //       if (
    //         certificate.title &&
    //         certificate.clause &&
    //         certificate.dateExpiry &&
    //         certificate.dateIssue
    //       ) {
    //         this.certificateList.push({ ...certificate });
    //         certificate = {};
    //       }
    //     }
    //   }
    // },
    fileChange() {
      const startTime = new Date().getTime();
      fileToBase64(this.uploadField, (base64) => {
        this.img = base64;
        const base64String = base64.replace("data:", "").replace(/^.+,/, "");
        imageOcr("/predict/ch_pp-ocrv3", { images: [base64String] }).then(
          (rs) => {
            if (rs.status === "000") {
              const { results } = rs;
              const result = results[0];
              const { data } = result;
              console.log(data);

              let all = "";
              for (let i = 0; i < data.length; i += 1) {
                const field = data[i];
                const { text } = field;
                all += text;
              }
              // this.saxCertificateList(data);
              const certNumIdx = all.indexOf("证书编号");
              const certNumReg = /OSV-[^\u4e00-\u9fff]+/;
              const issueDateIdx = all.indexOf("证书有效期");
              console.log(all);
              //console.log(certNumBegin);

              if (certNumIdx > -1) {
                // const certNumBegin = certNumIdx + 18;
                this.idCard.cert_num = certNumReg.exec(all)[0]
                  ? certNumReg.exec(all)[0]
                  : "未识别";
              }
              if (issueDateIdx > -1) {
                const lastIndex = all.lastIndexOf("-");
                const firstBegin = lastIndex - 10;
                this.idCard.issue_date = all.substring(firstBegin, lastIndex)
                  ? all.substring(firstBegin, lastIndex)
                  : "未识别";
                const firstEnd = lastIndex + 1;
                this.idCard.validity_term = all.substring(
                  lastIndex + 1,
                  firstEnd + 10
                )
                  ? all.substring(lastIndex + 1, firstEnd + 10)
                  : "未识别";
              }
            }
          }
        );
      });
    },
  },
  created() {},
  mounted() {
    this.idCard = { ...this.idCardEmpty };
  },
  watch: {},
};
</script>
<style lang="stylus">
.ocr-id-card
  .box-content
    overflow: hidden;
    background-color: #ececec;
    img
      width 100%
      height 100%
  .card-info
    .q-item
      div:first-child
        max-width 150px !important
        padding-left 20px
</style>
